package biznussoft.fieldservice360;
             
import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import biznussoft.fieldservice360.service.UnCaughtException;
import biznussoft.fieldservice360.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.ui.sfnative.SalesforceActivity;

public class HomeActivity extends SalesforceActivity {

    public RestClient client;
    RelativeLayout rLayout;
    public static HomeActivity mActivity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Setup view
		setContentView(R.layout.homepage);
		Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this));
		rLayout = (RelativeLayout) findViewById(R.id.rrlayout);
		mActivity = this;
	}
	
	
	@Override 
	public void onResume() {
		rLayout.setVisibility(View.INVISIBLE);
		super.onResume();
	}		
	
	@Override
	public void onResume(RestClient client) {
        // Keeping reference to rest client
        this.client = client; 
        mActivity.client = client;
        Session.sAccesToken = client.getAuthToken();
        Session.sInstanceUrl = client.getClientInfo().instanceUrl.toString();
        Log.i("NCS","Instance URL  :"+Session.sInstanceUrl+": :"+Session.sAccesToken);
		// Show everything
//       String query = "select id,Name, FirstName, LastName from User where Id="+"'"+client.getClientInfo().userId+"'";
//       String query ="select Id from FConnect__Employees__c where Last_Name__c ='Prokay' AND FConnect__First_Name__c='Jerry'";
       String query = "select id from FConnect__Group_Members__c where user__c="+"'"+client.getClientInfo().userId+"'";
       try {
		sendRequest(query);
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
        rLayout.setVisibility(View.VISIBLE);
	}

	public void accountAction(View v) {
		startActivity(new Intent(this, AccountsActivity.class));
	}
	public void myActivities(View v) {
		startActivity(new Intent(this, MyActivities.class));
	}
	public void inventoryAction(View v) {
		startActivity(new Intent(this, InventoryActivity.class));
	}
	
	public void contactAction(View v){
		startActivity(new Intent(this,ContactsActivity.class));
	}
	
	public void serviceAction(View v){
		startActivity(new Intent(this,ServiceOrderActivity.class));
	}
	
	public void logoutAction(View v){
		SalesforceSDKManager.getInstance().logout(this);
	}
	
	private void sendRequest(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);

		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {   
					Log.i("NCS","GroupMember is  :"+result);
					JSONObject jsonObject1 = new JSONObject(result.asString());
					JSONArray jsonArray = jsonObject1.getJSONArray("records");
					Log.i("NCS","jsonArray length  :"+jsonArray.getJSONObject(0).getString("Id"));
					Session.sID = jsonArray.getJSONObject(0).getString("Id");
					String query = "select  FirstName, LastName from User where Id="+"'"+client.getClientInfo().userId+"'";
					getOwnerName(query);
					
				} catch (Exception e) {
					onError(e);
				}               
			}

			@Override
			public void onError(Exception exception) {
              
			}     
		});
	}
	private void getOwnerName(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {                                                          
					Log.i("RGT","RestResponse is  :"+result);
					JSONArray records = result.asJSONObject().getJSONArray("records");
					Session.sFirstName = records.getJSONObject(0).getString("FirstName");
					Session.sLastName = records.getJSONObject(0).getString("LastName");
					
					
					String query ="select Id from FConnect__Employees__c where Last_Name__c ='"+Session.sLastName+"'"+"AND FConnect__First_Name__c='"+Session.sFirstName+"'"+" AND FConnect__Role__c='Technician'";
					 try {
							sendRequest1(query);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				} catch (Exception e) {                  
					onError(e);
				}               
			}

			@Override
			public void onError(Exception exception) {
              
			}
		});
	}
	
	private void sendRequest1(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);

		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {   
					Log.i("NCS","User is  :"+result);
				
					
				} catch (Exception e) {
					onError(e);
				}               
			}

			@Override
			public void onError(Exception exception) {
              
			}     
		});
	}
	/**
	 * Called when "Logout" button is clicked. 
	 * 
	 * @param v
	 */
	/*public void onLogoutClick(View v) {
		SalesforceSDKManager.getInstance().logout(this);
	}*/
	
	/**
	 * Called when "Clear" button is clicked. 
	 * 
	 * @param v
	 */
	/*public void onClearClick(View v) {
		listAdapter.clear();
	}*/	

	/**           
	 * Called when "Fetch Contacts" button is clicked
	 * 
	 * @param v
	 * @throws UnsupportedEncodingException 
	 */
	/*public void onFetchContactsClick(View v) throws UnsupportedEncodingException {
        sendRequest("SELECT Name FROM Contact");
	}*/

	/**
	 * Called when "Fetch Accounts" button is clicked
	 * 
	 * @param v
	 * @throws UnsupportedEncodingException 
	 */
	/*public void onFetchAccountsClick(View v) throws UnsupportedEncodingException {
		sendRequest("SELECT Name FROM Account");
	}*/	
	
	
}
